﻿using DongFangGuoKai.WCSPlatform.WebApi.Extensions;
using DongFangGuoKai.WCSPlatform.WebApi.Utils;
using DongFangGuoKai.WCSPlatform.WebApi.Utils.UtilModel;
using DongFangGuoKai.WCSPlatform.WebApi.Utils.WebSocketCommon;
using DongFangGuoKai.WMSPlatform.Commn.ExtendModule;
using DongFangGuoKai.WMSPlatform.Domain;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using S7.Net;
using System.Text;

namespace DongFangGuoKai.WCSPlatform.WebApi.Controllers.测试
{
    [Route("api/[controller]/[action]"), ApiController, Obsolete,ApiExplorerSettings(GroupName = nameof(WCSApiVersions.V1))]
    public class TestPlcController : ControllerBase
    {
        private readonly Plc plc;
        private readonly PlcDBAddress plcDBAddress;
        private readonly WebSocketHandler socketHandler;
        private readonly Utils.WebSocketCommon.WebSocketConnectManager socketManager;

        public TestPlcController(Plc plc, PlcDBAddress plcDBAddress, WebSocketHandler socketHandler, Utils.WebSocketCommon.WebSocketConnectManager socketManager)
        {
            this.plc = plc;
            this.plcDBAddress = plcDBAddress;
            this.socketHandler = socketHandler;
            this.socketManager = socketManager;
        }
        /// <summary>
        /// 测试使用 给出库箱子号写入值
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult<WCSApiResponse>> WriteBoxNumBer(int shu)
        {
            try
            {
                await Task.Run(async () => {
                    for (global::System.Int32 i = 0; i < shu; i++)
                    {
                       
                        var randomNum = new Random();
                        int randomNumber = randomNum.Next(10000, 99999);
                        string strVal = "C" + randomNumber.ToString();
                        plc.WriteString(plcDBAddress.DBNumber, plcDBAddress.OutPalletCode, strVal.ToHexStr());
                        var val = plc.ReadString(plcDBAddress.DBNumber, plcDBAddress.OutPalletCode).HexToStr();
                        if (val != strVal)
                        {
                            await Console.Out.WriteLineAsync("写入失败");
                        }
                        //plc.Write(plcDBAddress.PalletSortNumber, randomNum.Next(1000, 9999));
                        await Task.Delay(1000);
                        
                    }

                });
                return this.Success("写入成功");
            }
            catch (Exception ex)
            {
                return this.Fail(ex.Message);
            }
        }

        /// <summary>
        /// 测试使用 给入库箱子号写入值
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult<WCSApiResponse>> WriteSerialNumber(int shu)
        {
            try
            {
                await Task.Run(async () => {
                    for (global::System.Int32 i = 0; i < shu; i++)
                    {

                        var randomNum = new Random();
                        int randomNumber = randomNum.Next(10000, 99999);
                        string strVal = "C" + randomNumber.ToString();
                        plc.WriteString(plcDBAddress.DBNumber, plcDBAddress.InPalletCode, strVal.ToHexStr());
                        var val= plc.ReadString(plcDBAddress.DBNumber, plcDBAddress.InPalletCode).HexToStr();
                        if (val != strVal)
                        {
                            await Console.Out.WriteLineAsync("写入失败");
                        }
                        await Task.Delay(1000);

                    }

                });
                return this.Success("写入成功");
            }
            catch (Exception ex)
            {
                return this.Fail(ex.Message);
            }
        }

        /// <summary>
        /// 测试使用 AGV允许放货信号
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult<WCSApiResponse> AGVIsDropGoods(bool val)
        {
            try
            {
                plc.Write("DB1.DBX0.0", val);
                return this.Success("写入成功");
            }
            catch (Exception ex)
            {
                return this.Fail(ex.Message);
            }
        }

        /// <summary>
        /// 测试使用 AGV是否允许取料信号
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult<WCSApiResponse> AGVIsPickGoods(bool val)
        {
            try
            {
                plc.Write("DB1.DBX0.1", val);
                return this.Success("写入成功");
            }
            catch (Exception ex)
            {
                return this.Fail(ex.Message);
            }
        }

        /// <summary>
        /// 测试使用 AGV是否允许取料信号
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult<WCSApiResponse> StringTest(string str)
        {
            try
            {
                byte[] bytes = Encoding.ASCII.GetBytes(str);
                plc.WriteBytes(DataType.DataBlock, 1, 38, bytes); // 将字节数组写入 PLC
                byte[] readBytes = plc.ReadBytes(DataType.DataBlock, 1, 38, str.Length); // 从 PLC 读取字节数组
                string readStr = Encoding.ASCII.GetString(readBytes); // 将字节数组转换为字符串
                return this.Success("写入成功:" + readStr);
            }
            catch (Exception ex)
            {
                return this.Fail(ex.Message);
            }
        }


        [HttpGet]
        public ActionResult<WCSApiResponse> Read(string dbAddress)
        {
            var val = plc.Read(dbAddress);
            return this.Success(data: val);
        }


        [HttpGet]
        public ActionResult<WCSApiResponse> Write(string dbAddress, ushort val)
        {
            plc.Write(dbAddress, val);
            return this.Success(val);
        }

        [HttpGet]
        public ActionResult<WCSApiResponse> WriteString(int addr, string val)
        {
            // 将字节数组转换为十六进制字符串
            plc.WriteString(plcDBAddress.DBNumber, plcDBAddress.OutPalletCode, val.ToHexStr());
            return this.Success();
        }
        [HttpGet]
        public ActionResult<WCSApiResponse> ReadString(int addr)
        {
            var val = plc.ReadString(plcDBAddress.DBNumber, plcDBAddress.OutPalletCode).HexToStr();
            return this.Success(data: val);
        }
        [HttpGet]
        public ActionResult<WCSApiResponse> SendWebSocket(string msg)
        {
            socketManager.SendMessageToAllClients(new { palletCode="C10996",action= msg }.ToJson());
            return this.Success();
        }
    }
}
